<template>
  <div class="page">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <div class="left">
            <div class="info-group">
              <el-button class="add-btn" type="primary" @click="openDialog('add',null)">新增</el-button>
              <span class="total-count">共计{{ total }}条</span>
              <span class="warning">1和2数据较多</span>
            </div>
          </div>
          <div class="right">
            <el-form inline @submit.prevent>
              <el-form-item label="班级名">
                <el-input
                  v-model="searchForm.name"
                  placeholder="请输入班级名"
                  clearable
                  @clear="resetSearch"
                  @keyup.enter="handleSearch" />
              </el-form-item>
              <el-form-item label="班级编号">
                <el-input
                  v-model="searchForm.code"
                  placeholder="请输入班级编号"
                  clearable
                  @clear="resetSearch"
                  @keyup.enter="handleSearch" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
                <el-button @click="resetSearch">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </template>
      <el-table
        v-loading="loading"
        :data="clientData"
        style="width: 100%"
        empty-text="暂无数据"
        :table-layout="tableLayout">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="班级名称" />
        <el-table-column prop="code" label="班级编号" />
        <el-table-column prop="department_name" label="所属系部" />
        <el-table-column prop="created_at" label="创建时间">
          <template #default="{ row }">
            <span>{{ formatDate(row.created_at) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="180">
          <template #default="data">
            <div class="icon-group">
              <el-tooltip effect="light" content="编辑" placement="top">
                <el-button icon="Edit" type="primary" @click="openDialog('edit', data.row.id)" />
              </el-tooltip>
              <el-tooltip effect="light" content="查看学生" placement="top">
                <el-button icon="View" type="warning" @click="handleView(data.row.id)" />
              </el-tooltip>
              <el-tooltip effect="light" content="删除" placement="top">
                <el-button icon="Delete" type="danger" @click="handleDelete(data.row.id)" />
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="current"
        v-model:page-size="pageSize"
        background
        layout="total,  prev, pager, next, jumper"
        :total="total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange" />
    </el-card>
  </div>
  <el-dialog v-model="dialogVisible" :title="dialogFormTitle">
    <el-form ref="formRef" :model="dialogForm">
      <el-form-item label="班级名称" label-width="140px" prop="name">
        <el-input v-model="dialogForm.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="班级编号" label-width="140px" prop="code">
        <el-input v-model="dialogForm.code" autocomplete="off" />
      </el-form-item>
      <el-form-item label="部门" label-width="140px" prop="department">
        <el-select v-model="dialogForm.department" placeholder="请选择部门">
          <el-option label="计算机系" value="1" />
          <el-option label="会计系" value="2" />
          <el-option label="法学系" value="3" />
          <el-option label="外语系" value="4" />
          <el-option label="水利系" value="5" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="submitForm(dialogFormTitle === '新增班级' ? 'add' : 'edit')">确认</el-button>
          <!-- 通过标题来判断是新增还是编辑  在传入参数 -->
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getClazzList, deleteClazz, addClazz, updateClazz } from '@/api/clazz'
import { useClazzDetailStore } from '../../stores/clazz'
import { useDepartmentStore } from '../../stores/department'
const clazzDetailStore = useClazzDetailStore()
const departmentStore = useDepartmentStore()
const router = useRouter()
// 日期格式化函数
const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// // 部门ID到名称的映射
// const departmentMap = {
//   '1': '计算机系',
//   '2': '会计系',
//   '3': '法学系',
//   '4': '外语系',
//   '5': '水利系'
// }

// // 获取部门名称
// const getDepartmentName = (departmentId) => {
//   return departmentMap[departmentId] || '未知系部'
// }
// 总条数
const total = ref(0)
// 表格布局
const tableLayout = ref('fixed')
// 表格当前的显示数据
const clientData = ref([])
// 存储所有数据用于本地分页
const allData = ref([])
// 当前页数
const current = ref(1)
// 每页的显示条数
const pageSize = ref(10)
// 表格加载状态
const loading = ref(false)
// 框框的显示与隐藏
const dialogVisible = ref(false)

// 搜索相关
const searchForm = reactive({
  name: '',
  code: ''
})
// 对话框标题
const dialogFormTitle = ref('')
// 对话框表单数据
const dialogForm = reactive({
  id: null,
  name: '',
  code: '',
  department: ''
})
// 表单元素
const formRef = ref(null)
// 加载数据方法  稍微复杂
const loadData = async () => {
  // 加载数据显示加载状态
  loading.value = true
  try {
    // 获取所有数据
    const res = await getClazzList()
    if (res.status === 200) {
      allData.value = res.data.info || []
      // 应用本地搜索和分页  为了获取最新的数据 我们搜索和分页都要发请求
      applyLocalSearchAndPagination()
    } else {
      ElMessage.error(res.msg || '获取班级列表失败')
    }
    loading.value = false
  } catch (error) {
    loading.value = false
    ElMessage.error(error.message || '获取班级列表失败')
  }
}

// 本地搜索和分页函数
const applyLocalSearchAndPagination = () => {
  // 定义准备过虑的数据集
  let filteredData = allData.value

  // 本地搜索过滤
  if (searchForm.name.trim()) {
    filteredData = filteredData.filter(item =>
      item.name.toLowerCase().includes(searchForm.name.toLowerCase())
    )
  }

  if (searchForm.code.trim()) {
    filteredData = filteredData.filter(item =>
      item.code.toLowerCase().includes(searchForm.code.toLowerCase())
    )
  }

  // 设置总数
  total.value = filteredData.length

  // 本地分页
  const start = (current.value - 1) * pageSize.value
  const end = start + pageSize.value
  clientData.value = filteredData.slice(start, end)
}
const handleCurrentChange = value => {
  current.value = value
  applyLocalSearchAndPagination()
}

const handleSizeChange = value => {
  pageSize.value = value
  current.value = 1
  applyLocalSearchAndPagination()
}
// 搜索处理函数
const handleSearch = () => {
  current.value = 1 // 搜索时重置到第一页
  applyLocalSearchAndPagination()
}
// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchForm.code = ''
  current.value = 1
  applyLocalSearchAndPagination()
}
// 删除处理函数
const handleDelete = async id => {
  try {
    await ElMessageBox.confirm('确定要删除这条班级数据吗？', '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    // 调用删除API
    const res = await deleteClazz(id)
    if (res.status === 200) {
      // 从本地数据中删除
      const index = allData.value.findIndex(item => item.id === id)
      if (index > -1) {
        allData.value.splice(index, 1)
      }
    } else {
      ElMessage.error(res.msg || '删除班级失败')
      return
    }

    // 智能分页处理 - 当删除当前页最后一条数据时，自动跳转到上一页
    if (current.value > 1 && clientData.value.length === 1) {
      current.value--
    }

    ElMessage.success('删除成功!')

    // 重新应用本地搜索和分页
    applyLocalSearchAndPagination()
  } catch (error) {
    // 错误处理，区分用户取消和API调用失败
    if (error === 'cancel') {
      // 用户点击取消，不做任何操作
      console.log('用户取消了删除操作')
    } else {
      // API调用失败
      console.error('删除失败:', error)
      ElMessage.error(error.message || '删除失败，请重试')
    }
  }
}

// 打开对话框
const openDialog = (model, id) => {
  dialogFormTitle.value = model === 'add' ? '新增班级' : '编辑班级'
  dialogForm.id = id
  if (model === 'add') {
    dialogForm.name = ''
    dialogForm.code = ''
    dialogForm.department = ''
  } else {
    // 编辑模式，根据ID从本地数据中查找并填充表单
    const item = allData.value.find(item => item.id === id)
    if (item) {
      dialogForm.name = item.name
      dialogForm.code = item.code
      // 显示系部名称给用户，但存储系部ID用于提交
      dialogForm.department = item.department_name
    }
  }
  dialogVisible.value = true
}
const submitForm = async (model) => {
  try {
    await formRef.value.validate()

    // 准备提交的数据
    const submitData = { ...dialogForm }

    if (model === 'add') {
      await addClazz(submitData)
    } else {
      // 编辑时，需要将系部名称转换回系部ID
      // 看起来是有些复杂了 但是这样的使用体验会更好 以及后端接口数据校验才能跑通
      const departmentMap = {
        '计算机系': '1',
        '会计系': '2',
        '法学系': '3',
        '外语系': '4',
        '水利系': '5'
      }
      submitData.department = departmentMap[submitData.department] || submitData.department
      await updateClazz(submitData.id, submitData)
    }
    ElMessage.success('操作成功!')
    dialogVisible.value = false
    loadData()
  } catch (error) {
    ElMessage.error(error.message || '操作失败，请重试')
  }
}
const handleView = (id) => {
  // 存入id  (班级id 以及对应的系部id)
  departmentStore.setDepartmentId(allData.value.find(item => item.id === id)?.department)
  clazzDetailStore.setClazzId(id)
  router.push('/clazzDetail')
}
onMounted(() => {
  loadData()
})
</script>

<style scoped lang="scss">
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .left {
    display: flex;
    align-items: center;
    gap: 12px;

    .info-group {
      display: flex;
      align-items: center;
      gap: 8px;

      .total-count {
        font-size: 0.7rem;
        font-weight: 500;
        color: #606266;
        background: #f5f7fa;
        padding: 2px 8px;
        border-radius: 2px;
      }

      .warning {
        font-size: 0.65rem;
        font-weight: 500;
        color: #f56c6c;
        background: #fef0f0;
        padding: 2px 8px;
        border-radius: 2px;
      }
    }
  }

  .right {
    .el-form-item {
      margin-bottom: 0;
    }
  }
}

.icon-group {
  display: flex;
  gap: 8px;

  .el-button {
    padding: 4px 8px;
  }
}

.warning {
  font-size: 0.8rem;
  color: red;
}
</style>
